﻿
Imports System.DateTime
Imports System.Threading
Imports osi.root.template
Imports osi.root.envs
Imports osi.root.connector

Public Structure countevent(Of MAX_VALUE As _int64)
    Private Shared ReadOnly max As Int64

    Shared Sub New()
        max = +(alloc(Of MAX_VALUE)())
        k_assert(max > 0)
    End Sub

    Private i As Int32

    Public Function isset() As Boolean
        Return i > 0
    End Function

    Public Function wait(Optional ByVal ms As Int32 = Timeout.Infinite) As Boolean
        If ms < 0 Then
            ms = Timeout.Infinite
        End If
retry:
        If Interlocked.Decrement(i) >= 0 Then
            Return True
        Else
            Interlocked.Increment(i)
            Dim start_ms As Int64 = 0
            start_ms = Now().milliseconds()
            While i <= 0 AndAlso
                  (ms < 0 OrElse Now().milliseconds() - start_ms < ms)
                sleep(1)
            End While
            If ms < 0 OrElse Now().milliseconds() - start_ms < ms Then
                GoTo retry
            End If
            Return False
        End If
    End Function

    Public Function [set]() As Boolean
        If Interlocked.Increment(i) <= max Then
            Return True
        Else
            Interlocked.Decrement(i)
            Return False
        End If
    End Function
End Structure
